<template>
  <el-tree
    ref="tree"
    :node-key="nodeKey"
    :accordion="true"
    :check-strictly="true"
    :data="data"
    :props="defaultProps"
    show-checkbox
    @check="handleCheckChange"
    style="margin-top: 5px !important"
  ></el-tree>
</template>

<script>
export default {
  name: 'ztree',
  props: {
    nodeKey: {
      type: String, // tree数据
      default: () => {
        return 'id'
      },
    },
    parentId: {
      type: String, // tree数据
      default: () => {
        return 'parentId'
      },
    },
    data: {
      type: Array, // tree数据
      default: () => {
        return []
      },
    },
    defaultProps: {
      type: Object, // 配置选项
      default: () => {
        return {
          children: 'children',
          label: 'label',
        }
      },
    },
  },
  methods: {
    handleCheckChange(node, treeStatus) {
      let selected = treeStatus.checkedKeys.indexOf(node[this.nodeKey]) // -1未选中
      if (selected !== -1) {
        // 选中
        this.selectedParent(node)
        this.uniteChildSame(node, true)
      } else {
        // 未选中
        if (node[this.defaultProps.children].length !== 0) {
          this.uniteChildSame(node, false)
        }
      }
    },
    uniteChildSame(node, isSelected) {
      // 统一处理子节点为相同的勾选状态
      this.$refs.tree.setChecked(node[this.nodeKey], isSelected)
      for (let i = 0; i < node[this.defaultProps.children].length; i++) {
        this.uniteChildSame(node[this.defaultProps.children][i], isSelected)
      }
    },
    selectedParent(obj) {
      // 统一处理父节点为选中
      let currentNode = this.$refs.tree.getNode(obj)
      if (currentNode.parent.key !== undefined) {
        this.$refs.tree.setChecked(currentNode.parent, true)
        this.selectedParent(currentNode.parent)
      }
    },
  },
}
</script>

<style>
.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  color: #409eff;
  background: transparent;
}
</style>
